/*
 * anthor xiongj
 * 2015.3.21
 * 省、市、区、街道选择弹出框
 * 配置灵活，时间有限，还有很大改进空间
 * #这个为最简单的单个调用，设置有默认值
 * #pop-area为需要调用的对象
 *
 * 实例
 * #1
 //var areaData = "{province:{},city:{},district:{},street:{}}"
 //areabox.init($('.pop-area'), {data: areaData});
 * #2
 * #两个框，每一个为省市，一个为区，有联动
 //var areaData = [];
 //
 //areabox.init($('.pop-area'), {
 //    data: areaData, showRange: {start: 1, end: 2}, callBack: function (dom) {
 //        areabox.init($('.pop-area-dis'), {
 //            data: areaData,
 //            showRange: {start: 3, end: 3},
 //            parent_code: dom.attr('city')
 //        });
 //    }
 //});
 *#3
 *#各级数据通过ajax取得lqr
 *
 //areabox.init($('.pop-area'), {
 //    title: '选择省份',
 //    asyncDataApi: {
 //        province: '/api/index.php?r=common/region/get-all-province',
 //        city: '/api/index.php?r=common/region/get-all-city-by-province-id',
 //        district: '/api/index.php?r=common/region/get-all-area-by-city-id'
 //    },
 //    showRange: {start: 1, end: 3},
 //    placement: "bottom",
 //    callBack: function (dom) {
 //    }
 //});

 * */


define(function (require, exports, module) {

    var $ = require("jquery");
    require('./areabox.css')
    require("bootstrap.min");

    function box() {
        this.dom;
        this.me;
        this.areabox;
        this.options;
        this.saveValue = [];
        this.areaTypeArr = {
            1: {"key": "province", "name": "省份"},
            2: {"key": "city", "name": "城市"},
            3: {"key": "district", "name": "地区"},
            4: {"key": "street", "name": "街道"}
        };
        this.init = function (dom, option) {

            this.options = option;

            this.options = $.extend({
                title: '区域选择',
                data: '',
                showRange: {start: 1, end: 4},
                parent_code: 0,
                asyncDataApi: false,
                callBack: '',
                placement: "top"
            }, option);
            this.dom = $(dom);
            var me = this;

            //初始化显示层级
            var tab = [
                '<li><a href="#area_content_province" data-toggle="tab" class="area_tab_province">省份</a></li>',
                '<li><a href="#area_content_city" data-toggle="tab" class="area_tab_city">城市</a></li>',
                '<li><a href="#area_content_district" data-toggle="tab" class="area_tab_district">地区</a></li>',
                '<li><a href="#area_content_street" data-toggle="tab" class="area_tab_street">街道</a></li>'
            ];
            var content = [
                '<div class="tab-pane" id="area_content_province"></div>',
                '<div class="tab-pane  " id="area_content_city"></div>',
                '<div class="tab-pane  " id="area_content_district"></div>',
                '<div class="tab-pane  " id="area_content_street"></div>'
            ];
            var template_0 = '<div><div class="areabox"><ul id="area_tab" class="nav nav-tabs" >';
            var template_1 = '</ul><div id="area_tab_content" class="tab-content">';
            var template_2 = '</div>';

            me.template = template_0;
            $.each(tab, function (i, o) {
                if ((i + 1) >= me.options.showRange.start && (i + 1) <= me.options.showRange.end) {
                    me.template += o;
                }
            });
            this.template += template_1;
            $.each(content, function (i, o) {
                if ((i + 1) >= me.options.showRange.start && (i + 1) <= me.options.showRange.end) {
                    me.template += o;
                }
            });
            me.template = me.template + template_1;
            //初始化弹出框
            this.dom
                .popover({
                    content: $(me.template).html(),
                    html: true,
                    title: me.options.title,
                    placement: me.options.placement,
                    trigger: 'focus click'
                })

            var clickWindowHandler = function (event) {
                var target = $(event.target);
                var target_pop = target.parents('.popover').prev();
                if (target.prop('outerHTML') != me.dom.prop('outerHTML') && target_pop.prop('outerHTML') != me.dom.prop('outerHTML')) {
                    me.dom.popover('hide');
                    $(window).off('click.address', clickWindowHandler);
                }
            };

            //弹出框后的初始化
            this.dom.on('shown.bs.popover', function () {

                $(window).on('click.address', clickWindowHandler);

                me.areabox = dom.next('.popover').find('.popover-content .areabox');

                parent_code = me.options.parent_code ? me.options.parent_code : 0;
                me.show(me.options.showRange.start, me.options.parent_code);


                if ((typeof(me.dom.attr(me.areaTypeArr[me.options.showRange.start]['key'])) == 'undefined' || me.dom.attr(me.areaTypeArr[me.options.showRange.start]['key']) == 'undefined' )) {
                    parent_code = me.options.parent_code ? me.options.parent_code : 0;
                    me.show(me.options.showRange.start, me.options.parent_code);
                } else {
                    //如果DOM元素里有值，弹出时默认选中
                    if (typeof(me.dom.attr('province')) !== 'undefined' && me.dom.attr('province') != '') {
                        me.show(1, 0);
                        me.areabox.find('#area_content_province li').each(function (i, o) {
                            if ($(this).attr('code') == me.dom.attr('province')) {
                                me.click($(this), 'province');
                            }
                        });
                    }

                    if (typeof(me.dom.attr('city')) !== 'undefined' && me.dom.attr('city') != '') {
                        var parent_code = me.options.parent_code ? me.options.parent_code : me.dom.attr('province');
                        me.show(2, parent_code);
                        me.areabox.find('#area_content_city li').each(function (i, o) {
                            if ($(this).attr('code') == me.dom.attr('city')) {
                                me.click($(this), 'city');
                            }
                        });
                    }
                    if (typeof(me.dom.attr('district')) !== 'undefined' && me.dom.attr('district') != '') {
                        var parent_code = me.options.parent_code ? me.options.parent_code : me.dom.attr('city');
                        me.show(3, parent_code);
                        me.areabox.find('#area_content_district li').each(function (i, o) {
                            if ($(this).attr('code') == me.dom.attr('district')) {
                                me.click($(this), 'district');
                            }
                        });
                    }

                    if (typeof(me.dom.attr('street')) !== 'undefined' && me.dom.attr('street') != '') {
                        var parent_code = me.options.parent_code ? me.options.parent_code : me.dom.attr('district');
                        me.show(4, parent_code);
                        me.areabox.find('#area_content_street li').each(function (i, o) {
                            if ($(this).attr('code') == me.dom.attr('street')) {
                                me.click($(this), 'street');
                            }
                        });
                    }
                }
            });
        };

        //显示内容
        this.show = function (type, code) {
            var me = this;
            if (type >= me.options.showRange.start && type <= me.options.showRange.end) {

                var areatype = me.areaTypeArr[type]['key'], data = {};
                me.areabox.find('.area_tab_' + areatype).click();

                //填充数据
                if (this.options.asyncDataApi) {
                    me.getLevelData(type, code).then(function (res) {
                        if (res.retCode == 0) {
                            var data = res.data;
                            if (data.length < 1) {
                                var ptype = me.areaTypeArr[type - 1]['key'];
                                data = [{"code": me.saveValue[ptype].code, "name": me.saveValue[ptype].name}];
                            }
                            me.areabox.find('#area_content_' + areatype).html(me.makeElement(data, type));
                            //初始值设置
                            if (me.saveValue.length < 1) {
                                var name = '';
                                for (var i = 0; i < data.length; i++) {
                                    if (data[i].code == me.dom.attr(areatype)) {
                                        name = data[i].name;
                                    }
                                }
                                me.saveValue[areatype] = {name: name, code: me.dom.attr(areatype)}
                            }

                            //绑定点击
                            me.areabox.find('#area_content_' + areatype + ' li').on(
                                'click',
                                function () {
                                    if (areatype != undefined) {
                                        me.click($(this), areatype);
                                        me.show(type + 1, $(this).attr('code'))
                                    }
                                });

                        }
                    })
                } else {
                    data = me.options.data[type][code];
                }
                me.areabox.find('#area_content_' + areatype).html(this.makeElement(data));

                //绑定点击
                me.areabox.find('#area_content_' + areatype + ' li').on(
                    'click',
                    function () {
                        if (areatype != undefined) {
                            me.click($(this), areatype);
                            me.show(type + 1, $(this).attr('code'))
                        }
                    });

            } else {
                //到最后一个层,赋值
                var domValue = [];
                for (var type in me.areaTypeArr) {
                    var key = me.areaTypeArr[type]['key'];
                    if (key in me.saveValue) {
                        me.dom.attr(key, me.saveValue[key]['code']);
                        domValue.push(me.saveValue[key]['name'])
                    }
                }
                me.dom.val(domValue.join('-'));

                //关闭弹出框
                me.dom.popover('hide');
                $(window).off('click.address');
                //调用回调函数
                if (typeof(me.options.callBack) == 'function') {
                    me.options.callBack(me.dom);
                }
            }
        };
        this.getLevelData = function (type, code) {
            var typekey = this.areaTypeArr[type].key;
            var url = this.options.asyncDataApi[typekey];
            if (typekey == 'city') {
                url = url + '&code=' + code;
            } else if (typekey == "district") {
                url = url + '&code=' + code;
            } else if (typekey == "street") {
                url = url + '&code=' + code;
            }
            return $.get(url)
        };

        //元素点击事件
        this.click = function (dom_li, areatype) {
            //选中样式
            dom_li.siblings().removeClass('on');
            dom_li.addClass('on');
            var v = [];
            v['code'] = dom_li.attr('code');
            v['name'] = dom_li.attr('name');
            var me = this;
            me.saveValue[areatype] = v;
        }

        //组装元素
        this.makeElement = function (data, type) {
            var me = this;
            var ul = "<ul>";
            var li = '';
            $.each(data, function (i, o) {
                if (me.options.asyncDataApi) {
                    switch (type) {
                        case 1:
                            o.code = o.myscrm_ProvinceId || o.code;
                            o.name = o.ProvinceName || o.name;
                            break;
                        case 2:
                            o.code = o.myscrm_CityId || o.code;
                            o.name = o.CityName || o.name;
                            break;
                        case 3:
                            o.code = o.myscrm_AreaId || o.code;
                            o.name = o.AreaName || o.name;
                            break;
                    }

                }
                li += '<li code="' + o.code + '" name="' + o.name + '"  title="' + o.name + '">' + o.name + '</li>';
            })
            ul += li;
            ul += "</ul>";
            return ul;
        };
    }

    function init(dom, option) {
        var _box = new box();
        _box.init(dom, option);
    }

    exports.init = init;
});